<template>
  <div 
    class="alarm-floating-window"
    :style="windowStyle"
    @mousedown="bringToFront"
  >
    <!-- 窗口标题栏 -->
    <div 
      class="alarm-window-header"
      @mousedown="startDrag"
    >
      <div class="header-left">
        <i class="el-icon-bell"></i>
        <span class="header-title">实时报警</span>
        <el-tag 
          :type="connectionStatus === 'connected' ? 'success' : connectionStatus === 'connecting' ? 'warning' : 'danger'"
          size="mini"
          style="margin-left: 8px;"
        >
          <i :class="getConnectionIcon()"></i>
          {{ getConnectionText() }}
        </el-tag>
      </div>
      <div class="header-right">
        <el-button 
          type="text" 
          icon="el-icon-minus" 
          size="mini"
          @click="toggleMinimize"
          title="最小化"
        ></el-button>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="closeWindow"
          title="关闭"
        ></el-button>
      </div>
    </div>

    <!-- 窗口内容 -->
    <div class="alarm-window-content" v-show="!isMinimized">
      <div class="alarm-notification-container">
        <!-- 报警通知列表 -->
        <div class="alarm-list" v-if="alarmList.length > 0">
          <div 
            v-for="alarm in alarmList" 
            :key="alarm.alarmId || alarm.id"
            class="alarm-item"
            :class="{
              'alarm-active': alarm.status === '1',
              'alarm-ended': alarm.status === '0'
            }"
          >
            <div class="alarm-header">
              <div class="alarm-type">
                <i class="el-icon-warning" :class="getAlarmTypeClass(alarm.alarmType)"></i>
                <span class="alarm-description">{{ alarm.alarmDescription || getAlarmTypeText(alarm.alarmType) }}</span>
              </div>
              <div class="alarm-actions">
                <el-button 
                  type="text" 
                  icon="el-icon-close" 
                  size="mini"
                  @click="removeAlarm(alarm)"
                  v-if="alarm.status === '0'"
                ></el-button>
              </div>
            </div>
            <div class="alarm-content">
              <div class="alarm-info-item alarm-location-row">
                <span class="label">位置：</span>
                <span class="value">{{ getLocationWithSlot(alarm) }}</span>
                <span class="duration-value" v-if="alarm.duration !== undefined && alarm.duration !== null">
                  <span class="duration-label">间隔时间：</span>
                  <span class="duration-text">{{ formatDuration(alarm.duration) }}</span>
                </span>
              </div>
              <div class="alarm-info-item alarm-time-row">
                <span class="label">开始时间：</span>
                <span class="value">{{ formatTime(alarm.startTime) }}</span>
                <span v-if="alarm.status === '0' && alarm.endTime" class="end-time-value">
                  <span class="end-time-label">结束时间：</span>
                  <span class="end-time-text">{{ formatTime(alarm.endTime) }}</span>
                </span>
              </div>
            </div>
            <div class="alarm-status-badge" :class="alarm.status === '1' ? 'status-active' : 'status-ended'">
              {{ alarm.status === '1' ? '进行中' : '已结束' }}
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div class="alarm-empty" v-else>
          <i class="el-icon-bell"></i>
          <p>暂无报警信息</p>
        </div>
      </div>
    </div>

    <!-- 调整大小手柄 -->
    <div 
      class="resize-handle"
      @mousedown.stop="startResize"
    ></div>
  </div>
</template>

<script>
import { getAlarmWebSocketClient, closeAlarmWebSocket } from '@/utils/websocket'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'AlarmNotification',
  props: {
    // 最大显示的报警数量
    maxAlarms: {
      type: Number,
      default: 50
    },
    // 是否自动连接
    autoConnect: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      alarmList: [], // 报警列表
      connectionStatus: 'disconnected', // 连接状态：disconnected, connecting, connected, error
      wsClient: null,
      // 窗口位置和大小
      windowPosition: { x: 100, y: 100 },
      windowSize: { width: 400, height: 500 },
      isMinimized: false,
      // 拖拽状态
      isDragging: false,
      dragOffset: { x: 0, y: 0 },
      // 调整大小状态
      isResizing: false,
      resizeStart: { x: 0, y: 0, width: 0, height: 0 },
      // 最小尺寸
      minWidth: 300,
      minHeight: 200,
      // z-index管理
      zIndex: 1000,
      // 首次连接标记
      _isFirstConnection: true,
      _isFirstConnectionSet: false,
      // 已处理的报警ID集合（用于去重）
      processedAlarmIds: new Set(),
      // 报警去重键集合（槽号+报警类型+状态）
      alarmKeys: new Set()
    }
  },
  computed: {
    windowStyle() {
      return {
        left: `${this.windowPosition.x}px`,
        top: `${this.windowPosition.y}px`,
        width: `${this.windowSize.width}px`,
        height: this.isMinimized ? 'auto' : `${this.windowSize.height}px`,
        zIndex: this.zIndex
      }
    }
  },
  mounted() {
    // 从localStorage恢复位置和大小
    this.loadWindowState()
    // 监听鼠标事件
    document.addEventListener('mousemove', this.handleMouseMove)
    document.addEventListener('mouseup', this.handleMouseUp)
    // 连接WebSocket
    if (this.autoConnect) {
      this.connect()
    }
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('mousemove', this.handleMouseMove)
    document.removeEventListener('mouseup', this.handleMouseUp)
    // 保存窗口状态
    this.saveWindowState()
    // 断开WebSocket
    this.disconnect()
  },
  methods: {
    /**
     * 连接WebSocket
     */
    connect() {
      if (this.wsClient && this.wsClient.isConnected()) {
        console.log('WebSocket已连接')
        return
      }

      // 先移除之前的监听器，避免重复注册
      if (this.wsClient) {
        this.wsClient.off('open')
        this.wsClient.off('message')
        this.wsClient.off('error')
        this.wsClient.off('close')
        this.wsClient.off('reconnecting')
        this.wsClient.off('reconnect-success')
        this.wsClient.off('reconnect-failed')
      }

      this.connectionStatus = 'connecting'
      this.wsClient = getAlarmWebSocketClient()
      
      // 标记是否为首次连接（用于判断是否显示连接成功消息）
      // 使用组件实例属性，避免闭包问题
      if (!this._isFirstConnectionSet) {
        this._isFirstConnection = true
        this._isFirstConnectionSet = true
      }

      // 监听连接打开
      this.wsClient.on('open', () => {
        this.connectionStatus = 'connected'
        // 只在首次连接时显示消息，重连成功由reconnect-success事件处理
        if (this._isFirstConnection) {
          this.$message.success('报警通知连接成功')
          this._isFirstConnection = false
        }
      })

      // 监听消息
      this.wsClient.on('message', (data) => {
        console.log('AlarmNotification组件收到消息:', data)
        this.handleAlarmMessage(data)
      })

      // 监听错误
      this.wsClient.on('error', (error) => {
        console.error('WebSocket错误:', error)
        this.connectionStatus = 'error'
        // 只在首次连接失败时显示错误消息
        if (this._isFirstConnection) {
          this.$message.error('报警通知连接错误')
        }
      })

      // 监听关闭
      this.wsClient.on('close', () => {
        if (this.connectionStatus === 'connected') {
          this.connectionStatus = 'disconnected'
          // 只在手动关闭或异常关闭时显示消息，重连过程中的关闭不显示
          if (!this.wsClient.getIsReconnecting()) {
            this.$message.warning('报警通知连接已断开')
          }
        }
      })

      // 监听重连事件
      this.wsClient.on('reconnecting', (data) => {
        this.connectionStatus = 'connecting'
        this._isFirstConnection = false // 标记不是首次连接
        console.log('WebSocket正在重连，第' + data.attempts + '次尝试')
      })

      // 监听重连成功事件
      this.wsClient.on('reconnect-success', (data) => {
        this.connectionStatus = 'connected'
        this._isFirstConnection = false
        // 只在重连成功时显示消息（attempts > 0 表示是重连）
        if (data.attempts > 0) {
          this.$message.success('报警通知重连成功')
        }
      })

      // 监听重连失败事件
      this.wsClient.on('reconnect-failed', (data) => {
        this.connectionStatus = 'error'
        this._isFirstConnection = false
        this.$message.error(`报警通知重连失败，已尝试${data.attempts}次`)
      })

      // 连接
      this.wsClient.connect()
    },

    /**
     * 断开WebSocket连接
     */
    disconnect() {
      if (this.wsClient) {
        this.wsClient.off('open')
        this.wsClient.off('message')
        this.wsClient.off('error')
        this.wsClient.off('close')
        this.wsClient.off('reconnecting')
        this.wsClient.off('reconnect-success')
        this.wsClient.off('reconnect-failed')
        this.wsClient.close()
        this.wsClient = null
      }
      this.connectionStatus = 'disconnected'
    },

    /**
     * 处理报警消息
     */
    handleAlarmMessage(data) {
      console.log('收到报警消息:', data)
      
      // 如果数据是数组，批量处理
      if (Array.isArray(data)) {
        data.forEach(alarm => {
          if (alarm && (alarm.alarmId || alarm.id)) {
            this.addAlarm(alarm)
          }
        })
        return
      }
      
      // 如果数据不是对象，跳过
      if (!data || typeof data !== 'object') {
        console.warn('无效的报警消息数据:', data)
        return
      }
      
      // 根据消息类型处理
      if (data.type === 'alarm' || data.type === 'door_alarm') {
        // 新增报警 - 优先使用 data.data，如果没有则使用 data 本身
        const alarmData = data.data || data
        if (alarmData && (alarmData.alarmId || alarmData.id)) {
          this.addAlarm(alarmData)
        }
      } else if (data.type === 'alarm_end') {
        // 报警结束
        const alarmData = data.data || data
        if (alarmData && (alarmData.alarmId || alarmData.id)) {
          this.endAlarm(alarmData)
        }
      } else if (data.alarmId || data.id) {
        // 单个报警对象（没有 type 字段，直接是报警对象）
        this.addAlarm(data)
      } else {
        console.warn('无法识别的报警消息格式:', data)
      }
    },

    /**
     * 添加报警
     */
    addAlarm(alarm) {
      if (!alarm) return
      
      // 必须有报警ID才能添加
      const alarmId = alarm.alarmId || alarm.id
      if (!alarmId) {
        console.warn('报警数据缺少ID，跳过添加:', alarm)
        return
      }

      // 生成报警唯一键：槽号+报警类型+状态
      const slotNumber = alarm.slotNumber
      const alarmType = alarm.alarmType
      const status = alarm.status || '1'
      const alarmKey = `${slotNumber}_${alarmType}_${status}`

      // 先检查是否已存在（根据报警ID）- 这是最严格的检查
      const existingIndex = this.alarmList.findIndex(
        item => {
          const itemId = item.alarmId || item.id
          return itemId === alarmId
        }
      )

      if (existingIndex > -1) {
        // 报警已存在
        const existingAlarm = this.alarmList[existingIndex]
        const existingStatus = existingAlarm.status || '1'
        
        // 如果现有报警已经是进行中状态，且新报警也是进行中，则不更新（避免重复通知和闪烁）
        if (existingStatus === '1' && status === '1') {
          console.log('报警已存在且正在进行中，跳过重复添加:', alarmId)
          return
        }
        
        // 更新现有报警（状态变化时）
        this.$set(this.alarmList, existingIndex, { ...existingAlarm, ...alarm })
        
        // 更新报警键集合
        if (status === '1') {
          this.alarmKeys.add(alarmKey)
        } else {
          // 如果报警结束，移除对应的键
          const oldKey = `${slotNumber}_${alarmType}_1`
          this.alarmKeys.delete(oldKey)
        }
        return
      }

      // 如果是进行中的报警，检查是否已经存在相同的键（槽号+类型+状态）
      if (status === '1') {
        if (this.alarmKeys.has(alarmKey)) {
          console.log('报警已存在（相同槽号和类型），跳过重复添加:', alarmKey, alarmId)
          return
        }
      }

      // 新报警，添加到列表
      // 添加新报警到列表开头
      this.alarmList.unshift(alarm)
      
      // 限制列表长度
      if (this.alarmList.length > this.maxAlarms) {
        // 移除超出部分的报警键
        const removed = this.alarmList.slice(this.maxAlarms)
        removed.forEach(item => {
          const itemSlot = item.slotNumber
          const itemType = item.alarmType
          const itemStatus = item.status || '1'
          const itemKey = `${itemSlot}_${itemType}_${itemStatus}`
          this.alarmKeys.delete(itemKey)
        })
        this.alarmList = this.alarmList.slice(0, this.maxAlarms)
      }

      // 如果是新报警且状态为进行中，添加到键集合
      if (status === '1') {
        this.alarmKeys.add(alarmKey)
        // 播放报警声音提示（根据报警类型选择不同声音）
        this.playAlarmSound(alarm.alarmType)
      }
    },

    /**
     * 结束报警
     */
    endAlarm(alarm) {
      const index = this.alarmList.findIndex(
        item => (item.alarmId || item.id) === (alarm.alarmId || alarm.id)
      )
      if (index > -1) {
        const existingAlarm = this.alarmList[index]
        // 移除报警键（进行中状态的键）
        const slotNumber = existingAlarm.slotNumber || alarm.slotNumber
        const alarmType = existingAlarm.alarmType || alarm.alarmType
        const oldKey = `${slotNumber}_${alarmType}_1`
        this.alarmKeys.delete(oldKey)
        
        this.$set(this.alarmList, index, { 
          ...this.alarmList[index], 
          ...alarm,
          status: '0'
        })
      }
    },

    /**
     * 移除报警
     */
    removeAlarm(alarm) {
      const index = this.alarmList.findIndex(
        item => (item.alarmId || item.id) === (alarm.alarmId || alarm.id)
      )
      if (index > -1) {
        const removedAlarm = this.alarmList[index]
        // 移除报警键
        const slotNumber = removedAlarm.slotNumber
        const alarmType = removedAlarm.alarmType
        const status = removedAlarm.status || '1'
        const alarmKey = `${slotNumber}_${alarmType}_${status}`
        this.alarmKeys.delete(alarmKey)
        
        this.alarmList.splice(index, 1)
      }
    },


    /**
     * 获取报警类型文本
     */
    getAlarmTypeText(type) {
      const typeMap = {
        '1': '电源箱门开',
        '2': '槽控机门开'
      }
      return typeMap[type] || '未知报警'
    },

    /**
     * 获取报警类型样式类
     */
    getAlarmTypeClass(type) {
      return type === '1' ? 'type-power' : 'type-controller'
    },

    /**
     * 格式化时间
     */
    formatTime(time) {
      if (!time) return '-'
      return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
    },

    /**
     * 格式化持续时间
     */
    formatDuration(seconds) {
      if (seconds === null || seconds === undefined) return '-'
      if (seconds < 60) {
        return `${seconds}秒`
      } else if (seconds < 3600) {
        const minutes = Math.floor(seconds / 60)
        const secs = seconds % 60
        return `${minutes}分${secs}秒`
      } else {
        const hours = Math.floor(seconds / 3600)
        const minutes = Math.floor((seconds % 3600) / 60)
        const secs = seconds % 60
        return `${hours}小时${minutes}分${secs}秒`
      }
    },

    /**
     * 获取位置路径（工区 厂房 工段）
     */
    getLocationPath(alarm) {
      if (!alarm) return ''
      
      const parts = []
      if (alarm.areaName) {
        parts.push(alarm.areaName)
      }
      if (alarm.factoryName) {
        parts.push(alarm.factoryName)
      }
      if (alarm.sectionName) {
        parts.push(alarm.sectionName)
      }
      
      return parts.length > 0 ? parts.join(' ') : ''
    },

    /**
     * 获取位置和槽号（位置 槽号）
     */
    getLocationWithSlot(alarm) {
      if (!alarm) return ''
      
      const location = this.getLocationPath(alarm)
      const slotNumber = alarm.slotNumber
      
      if (location && slotNumber) {
        return `${location} ${slotNumber}`
      } else if (location) {
        return location
      } else if (slotNumber) {
        return `槽号：${slotNumber}`
      }
      
      return ''
    },

    /**
     * 播放报警声音提示
     * @param {String} alarmType 报警类型（1=电源箱门开，2=槽控机门开）
     */
    playAlarmSound(alarmType) {
      try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)()
        
        // 根据报警类型选择不同的声音
        let frequency = 800 // 默认频率
        let duration = 0.5 // 默认持续时间
        let soundType = 'single' // 默认单音
        
        if (alarmType === '1') {
          // 电源箱门开 - 高音短促
          frequency = 1000
          duration = 0.3
          soundType = 'single'
        } else if (alarmType === '2') {
          // 槽控机门开 - 中音双响
          frequency = 600
          duration = 0.4
          soundType = 'double'
        } else {
          // 默认 - 标准警报声
          frequency = 800
          duration = 0.5
          soundType = 'single'
        }
        
        if (soundType === 'double') {
          // 双响：先高后低
          this.playTone(audioContext, frequency * 1.2, 0.2, 0.3)
          setTimeout(() => {
            this.playTone(audioContext, frequency * 0.8, 0.2, 0.3)
          }, 200)
        } else {
          // 单响
          this.playTone(audioContext, frequency, duration, 0.3)
        }
      } catch (error) {
        console.warn('无法播放报警声音:', error)
      }
    },

    /**
     * 播放单个音调
     * @param {AudioContext} audioContext 音频上下文
     * @param {Number} frequency 频率（Hz）
     * @param {Number} duration 持续时间（秒）
     * @param {Number} volume 音量（0-1）
     */
    playTone(audioContext, frequency, duration, volume) {
      try {
        const oscillator = audioContext.createOscillator()
        const gainNode = audioContext.createGain()
        
        oscillator.connect(gainNode)
        gainNode.connect(audioContext.destination)
        
        oscillator.frequency.value = frequency
        oscillator.type = 'sine'
        
        gainNode.gain.setValueAtTime(volume, audioContext.currentTime)
        gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration)
        
        oscillator.start(audioContext.currentTime)
        oscillator.stop(audioContext.currentTime + duration)
      } catch (error) {
        console.warn('播放音调失败:', error)
      }
    },

    /**
     * 获取连接图标
     */
    getConnectionIcon() {
      const iconMap = {
        'connected': 'el-icon-success',
        'connecting': 'el-icon-loading',
        'disconnected': 'el-icon-error',
        'error': 'el-icon-error'
      }
      return iconMap[this.connectionStatus] || 'el-icon-question'
    },

    /**
     * 获取连接状态文本
     */
    getConnectionText() {
      const textMap = {
        'connected': '已连接',
        'connecting': '连接中...',
        'disconnected': '未连接',
        'error': '连接错误'
      }
      return textMap[this.connectionStatus] || '未知状态'
    },

    /**
     * 开始拖拽
     */
    startDrag(e) {
      if (this.isMinimized) return
      this.isDragging = true
      this.bringToFront()
      const rect = this.$el.getBoundingClientRect()
      this.dragOffset = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      }
      e.preventDefault()
    },

    /**
     * 开始调整大小
     */
    startResize(e) {
      this.isResizing = true
      this.bringToFront()
      this.resizeStart = {
        x: e.clientX,
        y: e.clientY,
        width: this.windowSize.width,
        height: this.windowSize.height
      }
      e.preventDefault()
      e.stopPropagation()
    },

    /**
     * 处理鼠标移动
     */
    handleMouseMove(e) {
      if (this.isDragging) {
        // 计算新位置，限制在窗口内
        const newX = e.clientX - this.dragOffset.x
        const newY = e.clientY - this.dragOffset.y
        
        // 限制在可视区域内
        const maxX = window.innerWidth - this.windowSize.width
        const maxY = window.innerHeight - 50 // 保留标题栏高度
        
        this.windowPosition.x = Math.max(0, Math.min(newX, maxX))
        this.windowPosition.y = Math.max(0, Math.min(newY, maxY))
      } else if (this.isResizing) {
        // 计算新大小
        const deltaX = e.clientX - this.resizeStart.x
        const deltaY = e.clientY - this.resizeStart.y
        
        const newWidth = Math.max(this.minWidth, this.resizeStart.width + deltaX)
        const newHeight = Math.max(this.minHeight, this.resizeStart.height + deltaY)
        
        // 限制在窗口内
        const maxWidth = window.innerWidth - this.windowPosition.x
        const maxHeight = window.innerHeight - this.windowPosition.y
        
        this.windowSize.width = Math.min(newWidth, maxWidth)
        this.windowSize.height = Math.min(newHeight, maxHeight)
      }
    },

    /**
     * 处理鼠标释放
     */
    handleMouseUp() {
      if (this.isDragging || this.isResizing) {
        this.saveWindowState()
      }
      this.isDragging = false
      this.isResizing = false
    },

    /**
     * 置顶窗口
     */
    bringToFront() {
      // 简单的z-index管理，每次点击增加z-index
      this.zIndex = Date.now() % 10000 + 1000
    },

    /**
     * 切换最小化
     */
    toggleMinimize() {
      this.isMinimized = !this.isMinimized
      this.saveWindowState()
    },

    /**
     * 关闭窗口
     */
    closeWindow() {
      this.$emit('close')
    },

    /**
     * 保存窗口状态到localStorage
     */
    saveWindowState() {
      try {
        const state = {
          position: this.windowPosition,
          size: this.windowSize,
          isMinimized: this.isMinimized
        }
        localStorage.setItem('alarmWindowState', JSON.stringify(state))
      } catch (e) {
        console.warn('保存窗口状态失败:', e)
      }
    },

    /**
     * 从localStorage加载窗口状态
     */
    loadWindowState() {
      try {
        const saved = localStorage.getItem('alarmWindowState')
        if (saved) {
          const state = JSON.parse(saved)
          if (state.position) {
            this.windowPosition = state.position
          }
          if (state.size) {
            this.windowSize = state.size
          }
          if (state.isMinimized !== undefined) {
            this.isMinimized = state.isMinimized
          }
        } else {
          // 默认位置：右上角
          this.windowPosition = {
            x: window.innerWidth - this.windowSize.width - 20,
            y: 80
          }
        }
      } catch (e) {
        console.warn('加载窗口状态失败:', e)
      }
    }
  }
}
</script>

<style scoped>
.alarm-floating-window {
  position: fixed;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  user-select: none;
  transition: box-shadow 0.3s;
}

.alarm-floating-window:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2);
}

.alarm-window-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  cursor: move;
  user-select: none;
  flex-shrink: 0;
}

.alarm-window-header:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-left i {
  font-size: 16px;
}

.header-title {
  font-weight: bold;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

.header-right .el-button {
  color: #fff;
  padding: 4px 8px;
}

.header-right .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.alarm-window-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 12px;
  background: #fff;
}

.alarm-notification-container {
  position: relative;
  min-height: 200px;
  height: 100%;
  overflow-y: auto;
}

.alarm-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.alarm-item {
  position: relative;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.alarm-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.alarm-item.alarm-active {
  border-left: 4px solid #f56c6c;
  background: #fef0f0;
}

.alarm-item.alarm-ended {
  border-left: 4px solid #909399;
  background: #f5f7fa;
  opacity: 0.8;
}

.alarm-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.alarm-type {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: bold;
  font-size: 14px;
}

.alarm-type i {
  font-size: 16px;
}

.alarm-type i.type-power {
  color: #f56c6c;
}

.alarm-type i.type-controller {
  color: #e6a23c;
}

.alarm-description {
  color: #303133;
}

.alarm-actions {
  display: flex;
  gap: 4px;
}

.alarm-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  font-size: 12px;
}

.alarm-info-item {
  display: flex;
  align-items: center;
}

.alarm-info-item .label {
  color: #909399;
  min-width: 60px;
}

.alarm-info-item .value {
  color: #303133;
  font-weight: 500;
}

.alarm-location-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: space-between;
}

.alarm-location-row .value {
  flex: 1;
  font-size: 14px;
}

.alarm-location-row .duration-value {
  display: flex;
  align-items: center;
  margin-left: 16px;
  font-size: 14px;
}

.alarm-location-row .duration-label {
  color: #909399;
  margin-right: 6px;
}

.alarm-location-row .duration-text {
  color: #303133;
  font-weight: 500;
}

.alarm-time-row {
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: space-between;
}

.alarm-time-row .value {
  flex: 1;
  font-size: 14px;
}

.alarm-time-row .end-time-value {
  display: flex;
  align-items: center;
  margin-left: 16px;
  font-size: 14px;
}

.alarm-time-row .end-time-label {
  color: #909399;
  margin-right: 6px;
}

.alarm-time-row .end-time-text {
  color: #303133;
  font-weight: 500;
}

.alarm-status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: bold;
}

.alarm-status-badge.status-active {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.alarm-status-badge.status-ended {
  background: #f5f7fa;
  color: #909399;
  border: 1px solid #909399;
}

.alarm-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #909399;
}

.alarm-empty i {
  font-size: 48px;
  margin-bottom: 12px;
  color: #c0c4cc;
}

.alarm-empty p {
  font-size: 14px;
  margin: 0;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 20px;
  height: 20px;
  cursor: nwse-resize;
  background: linear-gradient(135deg, transparent 0%, transparent 40%, #c0c4cc 45%, #c0c4cc 55%, transparent 60%, transparent 100%);
  z-index: 10;
}

.resize-handle:hover {
  background: linear-gradient(135deg, transparent 0%, transparent 40%, #409eff 45%, #409eff 55%, transparent 60%, transparent 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .alarm-content {
    grid-template-columns: 1fr;
  }
}
</style>

